package com.liu.qqRobot.q.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.q.entity.base.QGroupUser;
import com.liu.mybatisPlus.q.service.QGroupUserService;
import com.liu.qqRobot.q.service.SyncGroupUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncGroupUserServiceImpl implements SyncGroupUserService {

    @Resource
    private QGroupUserService qGroupUserService;

    @Override
    public void syncGroupUser() {
        List<Long> groupIdList = Arrays.asList(938354542L, 424907162L, 44044768L, 302418546L);
        groupIdList.forEach(groupId -> {
            List<QGroupUser> qGroupUserList = QQClientUtils.getGroupUser(groupId);
            QueryWrapper<QGroupUser> qGroupUserQueryWrapper = new QueryWrapper<>();
            qGroupUserQueryWrapper.eq("group_id", groupId);
            qGroupUserQueryWrapper.in("user_id", qGroupUserList.stream().map(QGroupUser::getUserId).collect(Collectors.toList()));
            List<QGroupUser> existQGroupUserList = qGroupUserService.list(qGroupUserQueryWrapper);
            Map<Long, QGroupUser> existQGroupUserMap = existQGroupUserList.stream().collect(Collectors.toMap(q -> q.getGroupId() + q.getUserId(), q -> q));
            List<QGroupUser> insertList = new ArrayList<>();
            List<QGroupUser> updateList = new ArrayList<>();
            qGroupUserList.forEach(q -> {
                QGroupUser qGroupUser = existQGroupUserMap.get(q.getGroupId() + q.getUserId());
                if (qGroupUser == null) {
                    insertList.add(q);
                } else {
                    updateList.add(q);
                }
            });
            if (CollUtil.isNotEmpty(insertList)) {
                qGroupUserService.saveBatch(insertList);
            }
            if (CollUtil.isNotEmpty(updateList)) {
                qGroupUserService.updateBatchById(updateList);
            }
        });
    }
}
